// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod crypto;
mod trust_tree;
mod distributed_trust;
mod trust_network_client;
mod complete_bittorrent;
mod torrent_parser;
mod weighted_approval;
mod content_verification;
mod reputation_system;
mod content_filter;
mod memory_monitor;
mod models;

use tauri::{State, Manager};
use tokio::sync::Mutex;
use std::sync::Arc;

// 导入所有必要的类型
use crate::{
    crypto::CryptoService,
    trust_tree::{TrustTree, TrustCertificate},
    distributed_trust::{DistributedTrustSystem, TrustChainValidation},
    complete_bittorrent::{CompleteBitTorrentService, DownloadProgress, TorrentFile},
    weighted_approval::{WeightedApprovalSystem, SignedApproval, VerifiedApproval},
    models::*,
};

struct AppState {
    crypto_service: Mutex<CryptoService>,
    trust_system: Mutex<DistributedTrustSystem>,
    bt_service: Mutex<CompleteBitTorrentService>,
    approval_system: Mutex<WeightedApprovalSystem>,
    memory_monitor: Mutex<memory_monitor::MemoryMonitor>,
}

#[tauri::command]
async fn initialize_network(state: State<'_, AppState>) -> Result<String, String> {
    let mut trust_system = state.trust_system.lock().await;
    trust_system.initialize_network().map_err(|e| e.to_string())
}

#[tauri::command]
async fn generate_keypair(
    state: State<'_, AppState>,
    peer_id: String,
) -> Result<KeyPairData, String> {
    let mut crypto_service = state.crypto_service.lock().await;
    crypto_service.generate_keypair(peer_id).map_err(|e| e.to_string())
}

#[tauri::command]
async fn start_file_download(
    state: State<'_, AppState>,
    torrent_path: String,
    content_approval: Option<ContentApproval>,
) -> Result<String, String> {
    let torrent_file = torrent_parser::TorrentParser::parse_torrent_file(std::path::Path::new(&torrent_path))?;
    
    let mut bt_service = state.bt_service.lock().await;
    bt_service.start_file_download(torrent_file, content_approval).await
}

#[tauri::command]
async fn get_download_progress(
    state: State<'_, AppState>,
    info_hash: String,
) -> Option<DownloadProgress> {
    let bt_service = state.bt_service.lock().await;
    bt_service.get_download_progress(&info_hash)
}

#[tauri::command]
async fn validate_trust_chain(
    state: State<'_, AppState>,
    peer_id: String,
) -> Result<TrustChainValidation, String> {
    let mut trust_system = state.trust_system.lock().await;
    trust_system.validate_trust_chain(&peer_id).await.map_err(|e| e.to_string())
}

#[tauri::command]
async fn submit_signed_approval(
    state: State<'_, AppState>,
    content_hash: String,
    approver_peer_id: String,
    comments: String,
) -> Result<SignedApproval, String> {
    let mut approval_system = state.approval_system.lock().await;
    let crypto_service = state.crypto_service.lock().await;
    
    approval_system.submit_signed_approval(
        &crypto_service,
        content_hash,
        approver_peer_id,
        comments,
    ).map_err(|e| e.to_string())
}

// 更多命令...

fn main() {
    let local_peer_id = "local_peer_".to_string() + &rand::random::<u32>().to_string();
    
    // 初始化各个服务
    let crypto_service = CryptoService::new();
    let trust_system = DistributedTrustSystem::new(local_peer_id.clone());
    let bt_service = CompleteBitTorrentService::new(
        std::path::PathBuf::from("./downloads"),
        trust_system.clone(), // 假设有clone方法
    );

    let approval_system = WeightedApprovalSystem::new(
        trust_tree.clone(), // 需要为 TrustTree 实现 Clone
        2.0,               // 批准阈值
        1,                 // 最低信任级别要求
    );

    let memory_monitor = memory_monitor::MemoryMonitor::new(1024); // 1GB内存限制

    tauri::Builder::default()
        .manage(AppState {
            crypto_service: Mutex::new(crypto_service),
            trust_system: Mutex::new(trust_system),
            bt_service: Mutex::new(bt_service),
            approval_system: Mutex::new(approval_system),
            memory_monitor: Mutex::new(memory_monitor),
        })
        .invoke_handler(tauri::generate_handler![
            initialize_network,
            generate_keypair,
            start_file_download,
            get_download_progress,
            validate_trust_chain,
            submit_signed_approval,
            // 添加其他命令...
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}